<template>
  <div class="app-container">
    <wms-form v-model="queryParams" :form-list="formList" @query="getList" label-width="108px" @export="handleExport">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="openStockDialog">盘点创建</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain @click="outboundExecution">出库执行</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="!hasSelected" @click="handleCancel">取消</el-button>
      </el-col>
    </wms-form>

    <el-drawer append-to-body v-model="stockDialogVisible" :title="`选择库存项`" direction="rtl" size="80%">
      <StockDialog v-if="stockDialogVisible" ref="stockDialogRef" :query-params="stockQueryParams" />

      <template #footer>
        <el-button @click="stockDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitStockSelection">确认选择</el-button>
      </template>
    </el-drawer>

    <wms-table row-key="taskId" :loading="loading" :data-list="taskList" :column="column" :pageInfo="queryParams"
      @get-list="getList" @selection-change="handleSelectionChange" />

  </div>
</template>

<script setup name="Check">
import { listTask, getTask, delTask, addTask, updateTask, delCheckTask, createCheckTask, outboundTask } from "@/api/wms/check";
import WmsTable from '@/components/WmsTable/index.vue'
import WmsForm from '@/components/WmsForm/index.vue'
import StockDialog from './stockDialog/stockDialog.vue'
import { data, column, formList } from './index.js'
import { ElMessage, ElMessageBox } from "element-plus";
import { directOut } from "@/api/wms/stock.js";
const dataReactive = reactive(data);
const { queryParams, form, rules } = toRefs(dataReactive);
const { proxy } = getCurrentInstance();
const { wms_task_status, wms_task_type, wms_task_sub_type } = proxy.useDict('wms_task_status', 'wms_task_type', 'wms_task_sub_type');
const taskList = ref([]);
const taskIds = ref([]);
const loading = ref(true);
const multiple = ref(true);
const single = ref(true);
// 表格引用
const tableRef = ref(null);
// 勾选状态
const hasSelected = ref(false);
// 存储勾选数据（可选）
const selectedRows = ref([]);
// 在原有代码中添加以下内容
const stockDialogVisible = ref(false);
const stockDialogRef = ref(null);
const stockQueryParams = ref({}); // 可以传入特定的查询参数

/** 查询任务查询列表 */
function getList() {
  loading.value = true;
  listTask(queryParams.value).then(response => {
    taskList.value = response.rows;
    queryParams.value.total = response.total;
    loading.value = false;

    //每次刷新后清空选择
    taskIds.value = [];
    hasSelected.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.vallue.dateRange = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  console.log("选中的数据:", selection);
  taskIds.value = selection.map(item => item.taskId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  hasSelected.value = selection.length > 0;
  console.log("hasSelected 更新为:", hasSelected.value);
  selectedRows.value = selection;
}

// 打开库存选择对话框
function openStockDialog() {
  stockDialogVisible.value = true;
}

/** 提交选择的库存项 */
async function submitStockSelection() {
  if (!stockDialogRef.value) return;

  const selectedStocks = stockDialogRef.value.getSelectedStocks();

  if (selectedStocks.length === 0) {
    ElMessage.warning('请至少选择一条库存记录');
    return;
  }

  try {
    // 调用创建盘点任务的API
    const response = await createCheckTask({
      ids: selectedStocks.map(stock => stock.stockId)
    });

    if (response.code === 200) {
      ElMessage.success('盘点任务创建成功');
      stockDialogVisible.value = false;
      getList(); // 刷新盘点任务列表
    } else {
      ElMessage.error(response.msg || '创建失败');
    }
  } catch (error) {
    console.error('创建盘点任务失败:', error);
    ElMessage.error(error);
  }
}

async function outboundExecution() {

  if (taskIds.value.length === 0) {
    ElMessage.warning('请至少选择一条出库任务');
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要执行选中的 ${taskIds.value.length} 条库存的出库任务吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    // 调用原材直发出库任务的API
    const response = await outboundTask({
      ids: taskIds.value
    });
    // if (response.code === 200) {
    //   ElMessage.success('原材直发出库任务创建成功');
    //   getList(); // 刷新盘点任务列表
    // } else {
    //   ElMessage.error(response.msg || '创建失败');
    // }
    ElMessage.success('出库任务执行成功');
    getList(); // 刷新盘点任务列表
  } catch (error) {
    console.error('出库任务执行失败:', error);
    // ElMessage.error(error);
  }
}


/** 取消按钮操作 */
async function handleCancel(row) {
  if (taskIds.value.length === 0) {
    ElMessage.warning('请至少选择一条数据');
  }
  try {
    await ElMessageBox.confirm(
      `确定要取消选中的 ${taskIds.value.length} 条任务吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    const response = await delCheckTask({
      ids: taskIds.value,
    })
    console.log("完整响应:", response);
    console.log("响应数据:", response.data);
    if (response.code === 200) {
      ElMessage.success('取消成功');
      getList(); // 刷新列表
      taskIds.value = []; // 清空选中项
    } else {
      ElMessage.error(response.msg || '取消失败');
    }
  } catch (err) {
    console.error('操作失败:', err)
  }
  // 清除选择（可选）
  tableRef.value?.clearSelection();
  hasSelected.value = false;
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('wms/task/export', {
    ...queryParams.value
  }, `task_${new Date().getTime()}.xlsx`)
}

getList();
</script>
